/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#ifndef __CPU_EDGE_FETCH_HH__
#define __CPU_EDGE_FETCH_HH__

#include "arch/utility.hh"
#include "arch/predecoder.hh"
#include "base/statistics.hh"
#include "base/timebuf.hh"
#include "config/the_isa.hh"
#include "cpu/pc_event.hh"
#include "mem/packet.hh"
#include "mem/port.hh"
#include "sim/eventq.hh"
#include "base/bitfield.hh"

class DerivEdgeCPUParams;

template <class Impl>
class SimpleEdgeFetch
{
  public:
    /** Typedefs from Impl. */
    typedef typename Impl::CPUPol CPUPol;
    typedef typename Impl::DynInst DynInst;
    typedef typename Impl::DynInstPtr DynInstPtr;
    typedef typename Impl::EdgeBlock Block;
    typedef typename Impl::EdgeBlockPtr BlockPtr;
    typedef typename Impl::CPU CPU;

    typedef typename CPUPol::Fetch2Map Fetch2Map;
    typedef typename CPUPol::TimeStruct TimeStruct;
    typedef typename CPUPol::BPredUnit BPredUnit;

    /** Typedefs from ISA. */
    typedef TheISA::MachInst MachInst;
    typedef TheISA::ExtMachInst ExtMachInst;
    typedef TheISA::BlockID BlockID;
    typedef TheISA::ChunkID ChunkID;
    typedef TheISA::InstID InstID;
    typedef TheISA::HeaderInfo HeaderInfo;
    typedef TheISA::ExitID ExitID;
    typedef TheISA::ExitType ExitType;

    /** IcachePort class for DefaultFetch.  Handles doing the
     * communication with the cache/memory.
     */
    class IcachePort : public Port
    {
      protected:
        /** Pointer to fetch. */
        SimpleEdgeFetch<Impl> *fetch;

      public:
        /** Default constructor. */
        IcachePort(SimpleEdgeFetch<Impl> *_fetch)
            : Port(_fetch->name() + "-iport", _fetch->cpu), fetch(_fetch)
        { }

        bool snoopRangeSent;

        virtual void setPeer(Port *port);

      protected:
        /** Atomic version of receive.  Panics. */
        virtual Tick recvAtomic(PacketPtr pkt);

        /** Functional version of receive.  Panics. */
        virtual void recvFunctional(PacketPtr pkt);

        /** Receives status change.  Other than range changing, panics. */
        virtual void recvStatusChange(Status status);

        /** Returns the address ranges of this device. */
        virtual void getDeviceAddressRanges(AddrRangeList &resp,
                                            bool &snoop)
        { resp.clear(); snoop = true; }

        /** Timing version of receive.  Handles setting fetch to the
         * proper status to start fetching. */
        virtual bool recvTiming(PacketPtr pkt);

        /** Handles doing a retry of a failed fetch. */
        virtual void recvRetry();
    };


  public:
    /** Overall fetch status. Used to determine if the CPU can
     * deschedule itsef due to a lack of activity.
     */
    enum FetchStatus {
        Active,
        Inactive
    };

    /** Individual thread status. */
    enum ThreadStatus {
        Running,
        Idle,
        Squashing,
        Blocked,
        Fetching,
        TrapPending,
        QuiescePending,
        SwitchOut,
        IcacheWaitResponse,
        IcacheWaitRetry,
        IcacheAccessComplete
    };

   /** Fetching status for EDGE ISA to differ head fetching from normal fetching*/
   enum EdgeFetchStatus {
       Head = 0,
       Normal
   };

    /** Fetching Policy, Add new policies here.*/
    enum FetchPriority {
        SingleThread,
        RoundRobin,
        Branch,
        IQ,
        LSQ
    };

  private:
    /** Fetch status. */
    FetchStatus _status;

    /** Edge Fetch status */
    EdgeFetchStatus edgeFetchStatus[Impl::MaxThreads];

    /** Per-thread status. */
    ThreadStatus fetchStatus[Impl::MaxThreads];

    /** Fetch policy. */
    FetchPriority fetchPolicy;

    /** List that has the threads organized by priority. */
    std::list<ThreadID> priorityList;

  public:
    /** DefaultFetch constructor. */
    SimpleEdgeFetch(CPU *_cpu, DerivEdgeCPUParams *params);

    /** Returns the name of fetch. */
    std::string name() const;

    /** Registers statistics. */
    void regStats();

    /** Returns the icache port. */
    Port *getIcachePort() { return icachePort; }

    /** Sets the main backwards communication time buffer pointer. */
    void setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer);

    /** Sets pointer to list of active threads. */
    void setActiveThreads(std::list<ThreadID> *at_ptr);

    /** Sets pointer to time buffer used to communicate to the next stage. */
    void setFetchQueue(TimeBuffer<Fetch2Map> *fq_ptr);

    /** Initialize stage. */
    void initStage();

    /** Tells the fetch stage that the Icache is set. */
    void setIcache();

    /** Processes cache completion event. */
    void processCacheCompletion(PacketPtr pkt);

    /** Begins the drain of the fetch stage. */
    bool drain();

    /** Resumes execution after a drain. */
    void resume();

    /** Tells fetch stage to prepare to be switched out. */
    void switchOut();

    /** Takes over from another CPU's thread. */
    void takeOverFrom();

    /** Checks if the fetch stage is switched out. */
    bool isSwitchedOut() { return switchedOut; }

    /** Tells fetch to wake up from a quiesce instruction. */
    void wakeFromQuiesce();

    /** Returns the PC of the head instruction of the ROB.
     * @todo: Probably remove this function as it returns only thread 0.
     */
    Addr readPC() { return PC[0]; }

    /** Returns the PC of a specific thread. */
    Addr readPC(ThreadID tid) { return PC[tid]; }

    Addr readBlockPC(ThreadID tid) { return blockPC[tid]; }

    /** Sets the PC of a specific thread. */
    void setPC(Addr val, ThreadID tid) { PC[tid] = val; }

    /** Reads the next PC of a specific thread. */
    Addr readNextPC(ThreadID tid) { return nextPC[tid]; }

    /** Sets the next PC of a specific thread. */
    void setNextPC(Addr val, ThreadID tid) { nextPC[tid] = val; }

    /** Reads the next NPC of a specific thread. */
    Addr readNextNPC(ThreadID tid) { return nextNPC[tid]; }

    /** Sets the next NPC of a specific thread. */
    void setNextNPC(Addr val, ThreadID tid) { nextNPC[tid] = val; }

  private:
    /** Changes the status of this stage to active, and indicates this
     * to the CPU.
     */
    inline void switchToActive();

    /** Changes the status of this stage to inactive, and indicates
     * this to the CPU.
     */
    inline void switchToInactive();

    /**
     * Looks up in the branch predictor to see if the next PC should be
     * either next PC+=MachInst or a branch target.
     * @param next_PC Next PC variable passed in by reference.  It is
     * expected to be set to the current PC; it will be updated with what
     * the next PC will be.
     * @param next_NPC Used for ISAs which use delay slots.
     * @return Whether or not a branch was predicted as taken.
     */
    bool lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC, Addr &next_NPC);

    /**
     * Fetches the cache line that contains fetch_PC.  Returns any
     * fault that happened.  Puts the data into the class variable
     * cacheData.
     * @param fetch_PC The PC address that is being fetched from.
     * @param ret_fault The fault reference that will be set to the result of
     * the icache access.
     * @param tid Thread id.
     * @return Any fault that occured.
     */
    bool fetchCacheLine(Addr fetch_PC, Fault &ret_fault, ThreadID tid);

    /** Squashes a specific thread and resets the PC. */
    inline void doSquash(const Addr &new_PC, const Addr &new_NPC, ThreadID tid);

    /** Squashes a specific thread and resets the PC. Also tells the CPU to
     * remove any instructions between fetch and decode that should be sqaushed.
     */
    void squashFromMap(const Addr &new_PC, const Addr &new_NPC,
                          const BlockID &seq_num, ThreadID tid);

    /** Checks if a thread is stalled. */
    bool checkStall(ThreadID tid) const;

    /** Updates overall fetch stage status; to be called at the end of each
     * cycle. */
    FetchStatus updateFetchStatus();

  public:
    /** Squashes a specific thread and resets the PC. Also tells the CPU to
     * remove any instructions that are not in the ROB. The source of this
     * squash should be the commit stage.
     */
    void squash(const Addr &new_PC, const Addr &new_NPC,
                const BlockID &seq_num, ThreadID tid);

    /** Ticks the fetch stage, processing all inputs signals and fetching
     * as many instructions as possible.
     */
    void tick();

    /** Checks all input signals and updates the status as necessary.
     *  @return: Returns if the status has changed due to input signals.
     */
    bool checkSignalsAndUpdate(ThreadID tid);


    void generateInst(ThreadID tid, TheISA::MachInst &inst_code, Addr pc,
            int inst_id, int chunk_id, TheISA::BlockStatus status);

    /** Does the actual fetching of instructions and passing them on to the
     * next stage.
     * @param status_change fetch() sets this variable if there was a status
     * change (ie switching to IcacheMissStall).
     */
    void fetch(bool &status_change);

    /**
     * If we in pre-execute mode, execute the current block once we
     * finish fetching it.
     * */
    bool preExecute(Addr &pred_NPC, ThreadID tid);

    /** Align a PC to the start of an I-cache block. */
    Addr icacheBlockAlignPC(Addr addr)
    {
        addr = TheISA::realPCToFetchPC(addr);
        return (addr & ~(cacheBlkMask));
    }

  private:
    /** Handles retrying the fetch access. */
    void recvRetry();

    /** Returns the appropriate thread to fetch, given the fetch policy. */
    ThreadID getFetchingThread(FetchPriority &fetch_priority);

    /** Returns the appropriate thread to fetch using a round robin policy. */
    ThreadID roundRobin();

    /** Returns the appropriate thread to fetch using the IQ count policy. */
    ThreadID iqCount();

    /** Returns the appropriate thread to fetch using the LSQ count policy. */
    ThreadID lsqCount();

    /** Returns the appropriate thread to fetch using the branch count
     * policy. */
    ThreadID branchCount();

    /** Get the current frame id for each inst blocks. */
    int getCurrFrameID();

    /** Decrease the frame id if an inst block is squashed. */
    void decCurrFrameID();

    /** Stall stage due to max frame limitation. */
    void stallStage(ThreadID tid)
    {
        stalls[tid].fetch = true;
    }

    /** Restore stage due to frames available again. */
    void unstallStage(ThreadID tid)
    {
        assert(stalls[tid].fetch);
        stalls[tid].fetch =false;
    }

    /** Consutruct EDGE header */
    void constructHeader(ExtMachInst inst, uint32_t offset, ThreadID tid) {
        assert(edgeFetchStatus[tid] == Head );

        headerInfo[TheISA::HeaderInfoSize - 1-offset/32] 
            |=( mbits(inst, 31, 28) >> ( offset % 32 ));
    }

    void clearHeaderInfo () {
        for ( int i = 0; i < TheISA::HeaderInfoSize; i ++ )
        headerInfo[i] = 0;
    }

  private:
    /** Pointer to the EDGECPU. */
    CPU *cpu;

    /** Time buffer interface. */
    TimeBuffer<TimeStruct> *timeBuffer;

    /** Wire to get decode's information from backwards time buffer. */
    typename TimeBuffer<TimeStruct>::wire fromMap;

    /** Wire to get iew's information from backwards time buffer. */
    typename TimeBuffer<TimeStruct>::wire fromExecute;

    /** Wire to get commit's information from backwards time buffer. */
    typename TimeBuffer<TimeStruct>::wire fromCommit;

    /** Internal fetch instruction queue. */
    TimeBuffer<Fetch2Map> *fetch2mapQueue;

    //Might be annoying how this name is different than the queue.
    /** Wire used to write any information heading to decode. */
    typename TimeBuffer<Fetch2Map>::wire toMap;

    /** Icache interface. */
    IcachePort *icachePort;

    /** BPredUnit. */
    BPredUnit branchPred;

       /** Predecoder. */
    TheISA::Predecoder predecoder;

    /** Current block ptr*/
    BlockPtr curEdgeBlockPtr;

    /** Per-thread fetch PC. */
    Addr PC[Impl::MaxThreads];

    Addr blockPC[Impl::MaxThreads];

    /** Per-thread next PC. */
    Addr nextPC[Impl::MaxThreads];

    Addr nextNPC[Impl::MaxThreads];

    /** Memory request used to access cache. */
    RequestPtr memReq[Impl::MaxThreads];

    /** Variable that tracks if fetch has written to the time buffer this
     * cycle. Used to tell CPU if there is activity this cycle.
     */
    bool wroteToTimeBuffer;

    /** Tracks how many instructions has been fetched this cycle. */
    int numInst;

    /** Source of possible stalls. */
    struct Stalls {
        bool fetch;
        bool map;
        bool execute;
        bool commit;
    };

    /** EDGE instruction header info*/
    HeaderInfo headerInfo;

    /** Instrunction chunk offsets*/
    Addr chunkOffset;
    /** Chunk size in bytes*/
    uint32_t chunkSize;
    /** Max chunks in a instruction block */
    uint32_t maxBlockSize;

    /** Instruction ID of current instruction in one block*/
    InstID instID;
    /** Chunk ID in current inst block*/
    ChunkID chunkID;
    /** Block ID of current inst */
    BlockID blockID;

    /** Current frame id for each inst block. */
    int currFrameID;

    /** Current inflight inst blocks fetch has generated. */
    int currInflightInstBlocks;

    /** Tracks which stages are telling fetch to stall. */
    Stalls stalls[Impl::MaxThreads];

    /** Map to fetch delay, in ticks. */
    unsigned mapToFetchDelay;

    /** Decode to fetch delay, in ticks. */
    unsigned decodeToFetchDelay;

    /** Execute to fetch delay, in ticks. */
    unsigned executeToFetchDelay;

    /** Commit to fetch delay, in ticks. */
    unsigned commitToFetchDelay;

    /** The width of fetch in instructions. */
    unsigned fetchWidth;

    /** Is the cache blocked?  If so no threads can access it. */
    bool cacheBlocked;

    /** The packet that is waiting to be retried. */
    PacketPtr retryPkt;

    /** The thread that is waiting on the cache to tell fetch to retry. */
    ThreadID retryTid;

    /** Cache block size. */
    int cacheBlkSize;

    /** Mask to get a cache block's address. */
    Addr cacheBlkMask;

    /** The cache line being fetched. */
    uint8_t *cacheData[Impl::MaxThreads];

    /** The PC of the cacheline that has been loaded. */
    Addr cacheDataPC[Impl::MaxThreads];

    /** Whether or not the cache data is valid. */
    bool cacheDataValid[Impl::MaxThreads];

    /** Size of instructions. */
    int instSize;

    /** Icache stall statistics. */
    Counter lastIcacheStall[Impl::MaxThreads];

    /** List of Active Threads */
    std::list<ThreadID> *activeThreads;

    /** Number of threads. */
    ThreadID numThreads;

    /** Number of threads that are actively fetching. */
    ThreadID numFetchingThreads;

    /** Thread ID being fetched. */
    ThreadID threadFetched;

    /** Checks if there is an interrupt pending.  If there is, fetch
     * must stop once it is not fetching PAL instructions.
     */
    bool interruptPending;

    /** Is there a drain pending. */
    bool drainPending;

    /** Records if fetch is switched out. */
    bool switchedOut;

    /** Are we in PreExecute mode? */
    bool preExecuteMode;

    /** Do we get a PERFECT branch predictor? */
    bool isPerfectBPred;

    /** Do we get a PERFECT branch type (and exit predictor) predictor? */
    bool isPerfectBTypePred;

    /** Do we get a PERFECT branch type (only) predictor? */
    bool isPerfectBTypeOnlyPred;

    /** Do we get a PERFECT sequential target predictor? */
    bool isPerfectSeqentialPred;

    /** Do we get a target-only predictor? */
    bool isTargetOnly;

    /** Do we get a PERFECT memory dependence unit? */
    bool isPerfectMemDep;

    /** Do we get a PERFECT predication mode? */
    bool isPerfectPredication;

    /** Update statistics related to instruction fetched. */
    void updateInstStats(DynInstPtr &inst);

    /** Update statistics related to head fetched. */
    void updateHeadStats(DynInstPtr &inst);

    /** Update statistics related to inst block fetching. */
    void updateInstBlockStats(BlockPtr &inst_block);

    // @todo: Consider making these vectors and tracking on a per thread basis.
    /** Stat for total number of cycles stalled due to an icache miss. */
    Stats::Scalar icacheStallCycles;
    /** Stat for total number of fetched instructions. */
    Stats::Scalar fetchedInsts;
    /** Stat for total number of fetched NOP insts. */
    //Stats::Scalar fetchedNopInsts;
    /** Stat for total number of fetched NOP insts in header. */
    //Stats::Scalar fetchedHeadNopInsts;
    /** Stat for total number of fetched MOV insts. */
    Stats::Scalar fetchedMovInsts;
    /** Stat for total number of fetched CONST insts. */
    Stats::Scalar fetchedConstInsts;
    /** Stat for total number of fetched TEST insts. */
    Stats::Scalar fetchedTestInsts;
    /** Stat for total number of fetched CONTROL insts. */
    Stats::Scalar fetchedControls;
    /** Stat for total number of fetched DIRECT CONTROL insts. */
    Stats::Scalar fetchedDirectControls;
    /** Stat for total number of fetched INDIRECT CONTROL insts. */
    Stats::Scalar fetchedIndirectControls;
    /** Stat for total number of fetched NULLIFY insts. */
    Stats::Scalar fetchedNullifies;
    /** Stat for total number of fetched MEMREF insts. */
    Stats::Scalar fetchedMemRefs;
    /** Stat for total number of fetched LOAD insts. */
    Stats::Scalar fetchedLoads;
    /** Stat for total number of fetched STORE insts. */
    Stats::Scalar fetchedStores;
    /** Stat for total number of fetched WRITE insts. */
    Stats::Scalar fetchedWrites;
    /** Stat for total number of fetched READ insts. */
    Stats::Scalar fetchedReads;
    /** Stat for toal number of fetched READ/WRITE insts. */
    Stats::Scalar fetchedReadWrites;
    /** Stat for total number of fetched insts with predication on true. */
    Stats::Scalar fetchedPredOnTrues;
    /** Stat for total number of fetched insts with predication on false. */
    Stats::Scalar fetchedPredOnFalses;

    /** Stat for total number of fetched NOP insts. */
    //Stats::Distribution fetchedNopInstsRatio;
    /** Stat for total number of fetched NOP insts in header. */
    //Stats::Distribution fetchedHeadNopInstsRatio;
    /** Stat for total number of fetched MOV insts. */
    Stats::Distribution fetchedMovInstsRatio;
    /** Stat for total number of fetched CONST insts. */
    Stats::Distribution fetchedConstInstsRatio;
    /** Stat for total number of fetched TEST insts. */
    Stats::Distribution fetchedTestInstsRatio;
    /** Stat for total number of fetched CONTROL insts. */
    Stats::Distribution fetchedControlsRatio;
    /** Stat for total number of fetched DIRECT CONTROL insts. */
    Stats::Distribution fetchedDirectControlsRatio;
    /** Stat for total number of fetched INDIRECT CONTROL insts. */
    Stats::Distribution fetchedIndirectControlsRatio;
    /** Stat for total number of fetched NULLIFY insts. */
    Stats::Distribution fetchedNullifiesRatio;
    /** Stat for total number of fetched MEMREF insts. */
    Stats::Distribution fetchedMemRefsRatio;
    /** Stat for total number of fetched LOAD insts. */
    Stats::Distribution fetchedLoadsRatio;
    /** Stat for total number of fetched STORE insts. */
    Stats::Distribution fetchedStoresRatio;
    /** Stat for total number of fetched WRITE insts. */
    Stats::Distribution fetchedWritesRatio;
    /** Stat for total number of fetched READ insts. */
    Stats::Distribution fetchedReadsRatio;
    /** Stat for toal number of fetched READ/WRITE insts. */
    Stats::Distribution fetchedReadWritesRatio;
    /** Stat for total number of fetched insts with predication on true. */
    Stats::Distribution fetchedPredOnTruesRatio;
    /** Stat for total number of fetched insts with predication on false. */
    Stats::Distribution fetchedPredOnFalsesRatio;
    
    /** Stat for distribution of number of operands of fetched insts. */
    Stats::Distribution fetchedNumOperands;
    /** Stat for ditribution of number of consumers of fetched insts. */
    Stats::Distribution fetchedNumConsumers;
    /** Stat for distribution of size of fetched inst blocks. */
    Stats::Distribution fetchedInstBlockSize;
    /** Stat for distribution of number of chunks in fetched inst blocks. */
    Stats::Distribution fetchedInstBlockSizeInChunks;
    
    /** Stat for total number of fetched blocks. */
    Stats::Scalar fetchedBlocks;
    /** Stat for total number of fetched instruction chunks. */
    Stats::Scalar fetchedChunks;
    /** Stat for total number of NOP blocks fetched. */
    Stats::Scalar fetchedNopBlocks;
    /** Stat for total number of cycles spent fetching. */
    Stats::Scalar fetchCycles;
    /** Stat for total number of cycles spent squashing. */
    Stats::Scalar fetchSquashCycles;
    /** Stat for total number of squashed inst blocks. */
    Stats::Scalar fetchSquashBlocks;
    /** Stat for total number of panic times due to block-misaligned prediction.*/
    Stats::Scalar fetchMisAlignedTimes;
    /** Stat for total number of cycles spent blocked due to other stages in
     * the pipeline.
     */
    Stats::Scalar fetchIdleCycles;
    /** Total number of cycles spent blocked. */
    Stats::Scalar fetchBlockedCycles;
    /** Total number of cycles spent in any other state. */
    Stats::Scalar fetchMiscStallCycles;
    /** Stat for total number of fetched cache lines. */
    Stats::Scalar fetchedCacheLines;
    /** Total number of outstanding icache accesses that were dropped
     * due to a squash.
     */
    Stats::Scalar fetchIcacheSquashes;
    /** Distribution of number of instructions fetched each cycle. */
    Stats::Distribution fetchNisnDist;
    /** Rate of how often fetch was idle. */
    Stats::Formula idleRate;
    /** Number of instruction fetched per cycle. */
    Stats::Formula fetchRate;
    /** Number of useful instructions fetched per cycle. */
    Stats::Formula usefulFetchRate;

    /** Stat of the number of inflight inst blocks oberved in fetch
     * stage. */
    Stats::Distribution fetchInflightInstBlocks;
};

#endif //__CPU_EDGE_FETCH_HH__
